package net.tngou.crawler.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.tngou.c4j.ml.Forecast;
import net.tngou.c4j.ml.Model;
import net.tngou.c4j.ml.Train;
import net.tngou.crawler.dao.DataDao;
import net.tngou.crawler.enums.StateEnum;
import net.tngou.crawler.pojo.Data;
import net.tngou.crawler.pojo.POJO;
import net.tngou.crawler.pojo.Urldata;

/**
 * 
 * @author tngou@tngou.net
 *
 */
public class MlService extends BaseService {

	public List<Data> getList(int page,int size) {
		DataDao dao = new DataDao();
		return dao.list(page, size);
	}
	
	public List<Model> getModels(Data data) {
		List<Model> list = new ArrayList<Model>();
		String value = data.getValue();
		JSONObject json=(JSONObject) JSON.parse(value);
		if(json==null)return list;
		Set<String> keys = json.keySet();
		for (String key : keys) {
			Model model = new Model(key, json.getString(key));
			list.add(model);								
		}
		return list;
	}
	
	/**
	 * 学习
	 * @param data
	 */
	public void study(Data data) {
		List<Model> list = getModels(data);
		list.forEach(e->{
			Train.Study(e);				
		});
		Urldata bean = new Urldata().get(data.getUrldata());
		if(bean!=null)
		{
			bean.setState(StateEnum.等待上传.ordinal());
			bean.update();
		}
	}
	
	/**
	 * 预测
	 * @param data
	 */
	public void forecast(Data data) {
		List<Model> list = getModels(data);
		boolean r = Forecast.Result(list);
		Urldata bean = new Urldata().get(data.getUrldata());
		if(bean!=null)
		{
			if(r) {
				bean.setState(StateEnum.等待上传.ordinal());
			}else
			{
				bean.setState(StateEnum.无效数据.ordinal());
			}
			bean.update();
		}
	}
	
	public static void main(String[] args) {
		MlService service = new MlService();
		Data data = new Data().get(1);
		List<Model> list = service.getModels(data);
		boolean r = Forecast.Result(list);
		System.err.println(r);
	}
}
